# apps/users/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.permissions import AllowAny
from rest_framework_simplejwt.tokens import RefreshToken
from apps.monitoring.utils import log_action

from .models import User
from ..user_device_map.models import UserDeviceMap

from .serializers import (
    UserLoginSerializer,
    UserInfoSerializer,
    UserCreateSerializer,
    UserUpdateSerializer,
    UserDevicePermissionSerializer
)


# 登录接口
class UserLoginView(APIView):
    permission_classes = [AllowAny]
    authentication_classes = []

    def post(self, request):
        # 最简单的用户名+密码明文校验
        uname = request.data.get('username')
        pwd = request.data.get('password')

        if not uname or not pwd:
            return Response({"message": "用户名和密码必填"}, status=400)

        try:
            user = User.objects.get(username=uname)
        except User.DoesNotExist:
            return Response({"message": "用户不存在"}, status=401)

        if user.password != pwd:
            return Response({"message": "密码错误"}, status=401)

        # 校验通过，返回用户信息
        return Response({
            "message": "登录成功",
            "user": {
                        "user_id": user.user_id,
                        "username": user.username,
                        "role": user.role,
                        "permission_level": user.permission_level
                    }
        }, status=200)

# 获取当前用户信息（模拟JWT）
class UserInfoView(APIView):
    permission_classes = [IsAuthenticated]
    def get(self, request):
        user = request.user
        return Response({
            'user_id': user.user_id,
            'username': user.username,
            'role': user.role,
            'permission_level': user.permission_level
        })

# 注册用户
class UserCreateView(APIView):
    permission_classes      = [AllowAny]
    authentication_classes  = []

    def post(self, request):
        ser = UserCreateSerializer(data=request.data)
        if not ser.is_valid():
            return Response({"message": ser.errors}, status=400)

        new_user = ser.save()
        # ---- 写日志 ------------------------------------------------------
        log_action(
            action_type='用户创建',
            user=request.user if request.user.is_authenticated else None,
            old_value=None,
            new_value=f"{new_user.username} (level {new_user.permission_level})"
        )
        return Response({"message": "User created successfully"}, status=201)

# 更新用户信息
class UserUpdateView(APIView):
    permission_classes      = [AllowAny]
    authentication_classes  = []

    def put(self, request, user_id):
        try:
            user = User.objects.get(user_id=user_id)
        except User.DoesNotExist:
            return Response({"message": "User not found"}, status=404)

        # 检查请求体是否为空
        if not request.data:
            return Response({"message": "No fields provided for update"}, status=400)
        
        old_info = {
            "username": user.username,
            "role": user.role,
            "permission_level": user.permission_level,
        }
        ser = UserUpdateSerializer(user, data=request.data, partial=True)
        if not ser.is_valid():
            return Response({"message": ser.errors}, status=400)

        ser.save()
        log_action(
            action_type='用户修改',
            user=request.user if request.user.is_authenticated else None,
            old_value=old_info,
            new_value=ser.validated_data
        )
        return Response({"message": "User updated successfully"})


# 删除用户
class UserDeleteView(APIView):
    permission_classes      = [AllowAny]
    authentication_classes  = []

    def delete(self, request, user_id):
        try:
            user = User.objects.get(user_id=user_id)
        except User.DoesNotExist:
            return Response({"message": "User not found"}, status=404)

        log_action(
            action_type='用户删除',
            user=request.user if request.user.is_authenticated else None,
            old_value=user.username,
            new_value=None
        )
        user.delete()
        return Response({"message": "User deleted successfully"})

# 用户权限分配接口
class UserPermissionAssignView(APIView):
    permission_classes      = [AllowAny]
    authentication_classes  = []

    def post(self, request):
        ser = UserDevicePermissionSerializer(data=request.data)
        if not ser.is_valid():
            return Response({"message": ser.errors}, status=400)

        mapping, created = UserDeviceMap.objects.update_or_create(
            user_id   = ser.validated_data['user_id'],
            device_id = ser.validated_data['device_id'],
            defaults  = {'permission': ser.validated_data['permission']}
        )
        # 写日志
        log_action(
            action_type='权限分配',
            user=request.user if request.user.is_authenticated else None,
            device=mapping.device,
            old_value=f"permission={mapping.permission}" if not created else None,
            new_value=ser.validated_data
        )
        return Response({"message": f"Permission {'created' if created else 'updated'} successfully!"})

# 返回所有用户
class UserListView(APIView):
    """返回全部用户；管理员前端才会调用"""
    permission_classes      = [AllowAny]      # ← 允许任何人访问
    authentication_classes  = []              # ← 不用令牌

    def get(self, request):
        users = User.objects.all().order_by('username')
        data = [{
            "user_id": u.user_id,
            "username": u.username,
            "email": u.email,
            "phone": u.phone,
            "reg_time": u.reg_time.strftime('%Y-%m-%d %H:%M:%S') if u.reg_time else '',
            "role": u.role,
            "permission_level": u.permission_level
        } for u in users]
        return Response(data, status=200)